package com.example.aidlclientdemo;

import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author 猿小蔡
 * @since 2025/6/28
 */
public class SocketServer {
    private static final int PORT = 8888;
    private ServerSocket serverSocket;
    private boolean isRunning = false;

    public void start() {
        isRunning = true;
        new Thread(() -> {
            try {
                serverSocket = new ServerSocket(PORT);
                Log.i("SERVER", "Server started on port " + PORT);

                while (isRunning) {
                    Socket client = serverSocket.accept();
                    Log.i("SERVER", "Client connected: " + client.getInetAddress());

                    // 处理客户端连接
                    new Thread(new ClientHandler(client)).start();
                }
            } catch (IOException e) {
                Log.e("SERVER", "Error: " + e.getMessage());
            }
        }).start();
    }

    public void stop() {
        try {
            isRunning = false;
            if (serverSocket != null) {
                serverSocket.close();
            }
        } catch (IOException e) {
            Log.e("SERVER", "Error closing server: " + e.getMessage());
        }
    }

    private static class ClientHandler implements Runnable {
        private final Socket clientSocket;

        public ClientHandler(Socket socket) {
            this.clientSocket = socket;
        }

        @Override
        public void run() {
            try (
                BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)
            ) {
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    Log.i("SERVER", "Received: " + inputLine);

                    // 回复客户端
                    String response = "ECHO: " + inputLine;
                    out.println(response);
                    Log.i("SERVER", "Sent: " + response);
                }
            } catch (IOException e) {
                Log.e("SERVER", "Client error: " + e.getMessage());
            } finally {
                try {
                    clientSocket.close();
                } catch (IOException e) {
                    Log.e("SERVER", "Error closing client socket");
                }
            }
        }
    }
}
